#include "modernui.h"
#include "outputsettings.h"
#include <QPainter>
#include <QPainterPath>
#include <QLinearGradient>
#include <QRadialGradient>
#include <QFontMetrics>
#include <QApplication>
#include <QWheelEvent>
#include <QEasingCurve>
#include <QDebug>
#include <QDate>
#include <QResizeEvent>
#include <cmath>

// Modern Card Implementation
ModernCard::ModernCard(QWidget *parent)
    : QFrame(parent)
    , m_elevation(2.0)
    , m_elevationAnimation(nullptr)
    , m_shadowEffect(nullptr)
    , m_pressed(false)
{
    setupUI();
}

ModernCard::ModernCard(const QString& title, const QString& subtitle, QWidget *parent)
    : QFrame(parent)
    , m_elevation(2.0)
    , m_elevationAnimation(nullptr)
    , m_shadowEffect(nullptr)
    , m_pressed(false)
{
    setupUI();
    setTitle(title);
    setSubtitle(subtitle);
}

void ModernCard::setupUI()
{
    setFrameStyle(QFrame::NoFrame);
    setAttribute(Qt::WA_Hover, true);
    
    m_layout = new QVBoxLayout(this);
    m_layout->setContentsMargins(24, 20, 24, 20);
    m_layout->setSpacing(8);
    
    // Title label
    m_titleLabel = new QLabel();
    m_titleLabel->setStyleSheet(
        "QLabel {"
        "   font-size: 18px;"
        "   font-weight: 600;"
        "   color: #1a1a1a;"
        "   margin: 0;"
        "}"
    );
    m_titleLabel->hide();
    m_layout->addWidget(m_titleLabel);
    
    // Subtitle label
    m_subtitleLabel = new QLabel();
    m_subtitleLabel->setStyleSheet(
        "QLabel {"
        "   font-size: 14px;"
        "   font-weight: 400;"
        "   color: #666666;"
        "   margin: 0;"
        "}"
    );
    m_subtitleLabel->hide();
    m_layout->addWidget(m_subtitleLabel);
    
    // Content layout
    m_contentLayout = new QVBoxLayout();
    m_contentLayout->setContentsMargins(0, 8, 0, 0);
    m_contentLayout->setSpacing(16);
    m_layout->addLayout(m_contentLayout);
    
    // Setup elevation animation
    m_elevationAnimation = new QPropertyAnimation(this, "elevation", this);
    m_elevationAnimation->setDuration(150);
    m_elevationAnimation->setEasingCurve(QEasingCurve::OutCubic);
    
    updateShadow();
    
    // Apply modern styling
    setStyleSheet(
        "ModernCard {"
        "   background-color: #ffffff;"
        "   border-radius: 12px;"
        "   border: none;"
        "}"
    );
}

void ModernCard::setTitle(const QString& title)
{
    m_titleLabel->setText(title);
    m_titleLabel->setVisible(!title.isEmpty());
}

void ModernCard::setSubtitle(const QString& subtitle)
{
    m_subtitleLabel->setText(subtitle);
    m_subtitleLabel->setVisible(!subtitle.isEmpty());
}

void ModernCard::setContentWidget(QWidget* widget)
{
    if (m_contentWidget) {
        m_contentLayout->removeWidget(m_contentWidget);
        m_contentWidget->deleteLater();
    }
    
    m_contentWidget = widget;
    if (widget) {
        m_contentLayout->addWidget(widget);
    }
}

void ModernCard::setElevation(qreal elevation)
{
    if (qFuzzyCompare(m_elevation, elevation))
        return;
        
    m_elevation = elevation;
    updateShadow();
    update();
}

void ModernCard::updateShadow()
{
    // Temporarily disable shadow effects to fix painter issues
    // TODO: Implement CSS-style box-shadow alternative
    if (m_shadowEffect) {
        delete m_shadowEffect;
        m_shadowEffect = nullptr;
    }
    setGraphicsEffect(nullptr);
}

void ModernCard::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event)
    
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);
    
    // Draw shadow manually (CSS-style box-shadow alternative)
    if (m_elevation > 0) {
        int shadowOffset = m_elevation * 2;
        int shadowBlur = m_elevation * 4;
        QColor shadowColor(0, 0, 0, 40 + m_elevation * 10);
        
        // Draw multiple shadow layers for blur effect
        for (int i = 0; i < shadowBlur; i++) {
            qreal alpha = shadowColor.alphaF() * (1.0 - (qreal)i / shadowBlur);
            QColor layerColor = shadowColor;
            layerColor.setAlphaF(alpha);
            
            QPainterPath shadowPath;
            QRect shadowRect = rect().adjusted(-i, shadowOffset - i, i, shadowOffset + i);
            shadowPath.addRoundedRect(shadowRect, 12 + i, 12 + i);
            
            painter.fillPath(shadowPath, layerColor);
        }
    }
    
    // Draw card background
    QPainterPath path;
    path.addRoundedRect(rect(), 12, 12);
    
    painter.fillPath(path, QColor(255, 255, 255));
    
    // Draw subtle border
    painter.setPen(QPen(QColor(0, 0, 0, 10), 1));
    painter.drawPath(path);
}

void ModernCard::enterEvent(QEnterEvent *event)
{
    Q_UNUSED(event)
    
    if (!m_pressed) {
        m_elevationAnimation->stop();
        m_elevationAnimation->setEndValue(4.0);
        m_elevationAnimation->start();
    }
}

void ModernCard::leaveEvent(QEvent *event)
{
    Q_UNUSED(event)
    
    if (!m_pressed) {
        m_elevationAnimation->stop();
        m_elevationAnimation->setEndValue(2.0);
        m_elevationAnimation->start();
    }
}

void ModernCard::mousePressEvent(QMouseEvent *event)
{
    Q_UNUSED(event)
    
    m_pressed = true;
    m_elevationAnimation->stop();
    m_elevationAnimation->setEndValue(1.0);
    m_elevationAnimation->start();
}

void ModernCard::mouseReleaseEvent(QMouseEvent *event)
{
    Q_UNUSED(event)
    
    m_pressed = false;
    m_elevationAnimation->stop();
    m_elevationAnimation->setEndValue(underMouse() ? 4.0 : 2.0);
    m_elevationAnimation->start();
}

// Modern Button Implementation
ModernButton::ModernButton(QWidget *parent)
    : QPushButton(parent)
    , m_style(Filled)
    , m_elevation(2.0)
    , m_rippleColor(QColor(255, 255, 255, 80))
    , m_rippleRadius(0)
    , m_rippleOpacity(0)
    , m_hoverProgress(0)
{
    setupAnimations();
    setButtonStyle(m_style);
}

ModernButton::ModernButton(const QString& text, QWidget *parent)
    : QPushButton(text, parent)
    , m_style(Filled)
    , m_elevation(2.0)
    , m_rippleColor(QColor(255, 255, 255, 80))
    , m_rippleRadius(0)
    , m_rippleOpacity(0)
    , m_hoverProgress(0)
{
    setupAnimations();
    setButtonStyle(m_style);
}

ModernButton::ModernButton(const QString& text, ButtonStyle style, QWidget *parent)
    : QPushButton(text, parent)
    , m_style(style)
    , m_elevation(2.0)
    , m_rippleColor(QColor(255, 255, 255, 80))
    , m_rippleRadius(0)
    , m_rippleOpacity(0)
    , m_hoverProgress(0)
{
    setupAnimations();
    setButtonStyle(style);
}

void ModernButton::setupAnimations()
{
    setAttribute(Qt::WA_Hover, true);
    
    // Ripple animation
    m_rippleAnimation = new QPropertyAnimation(this, "rippleRadius", this);
    m_rippleAnimation->setDuration(300);
    m_rippleAnimation->setEasingCurve(QEasingCurve::OutCubic);
    
    m_rippleTimer = new QTimer(this);
    m_rippleTimer->setSingleShot(true);
    m_rippleTimer->setInterval(300);
    connect(m_rippleTimer, &QTimer::timeout, this, &ModernButton::updateRipple);
    
    // Elevation animation
    m_elevationAnimation = new QPropertyAnimation(this, "elevation", this);
    m_elevationAnimation->setDuration(150);
    m_elevationAnimation->setEasingCurve(QEasingCurve::OutCubic);
    
    // Hover animation
    m_hoverAnimation = new QPropertyAnimation(this, "hoverProgress", this);
    m_hoverAnimation->setDuration(200);
    m_hoverAnimation->setEasingCurve(QEasingCurve::OutCubic);
    
    updateShadow();
}

void ModernButton::setButtonStyle(ButtonStyle style)
{
    m_style = style;
    
    QString styleSheet;
    switch (style) {
    case Filled:
        styleSheet = 
            "ModernButton {"
            "   background-color: #007AFF;"
            "   color: white;"
            "   border: none;"
            "   border-radius: 8px;"
            "   font-size: 14px;"
            "   font-weight: 500;"
            "   padding: 12px 24px;"
            "   min-height: 20px;"
            "}"
            "ModernButton:hover {"
            "   background-color: #0056CC;"
            "}"
            "ModernButton:pressed {"
            "   background-color: #004499;"
            "}";
        m_rippleColor = QColor(255, 255, 255, 80);
        break;
        
    case Outlined:
        styleSheet = 
            "ModernButton {"
            "   background-color: transparent;"
            "   color: #007AFF;"
            "   border: 2px solid #007AFF;"
            "   border-radius: 8px;"
            "   font-size: 14px;"
            "   font-weight: 500;"
            "   padding: 10px 22px;"
            "   min-height: 20px;"
            "}"
            "ModernButton:hover {"
            "   background-color: rgba(0, 122, 255, 0.1);"
            "}"
            "ModernButton:pressed {"
            "   background-color: rgba(0, 122, 255, 0.2);"
            "}";
        m_rippleColor = QColor(0, 122, 255, 60);
        break;
        
    case Text:
        styleSheet = 
            "ModernButton {"
            "   background-color: transparent;"
            "   color: #007AFF;"
            "   border: none;"
            "   border-radius: 8px;"
            "   font-size: 14px;"
            "   font-weight: 500;"
            "   padding: 12px 16px;"
            "   min-height: 20px;"
            "}"
            "ModernButton:hover {"
            "   background-color: rgba(0, 122, 255, 0.1);"
            "}"
            "ModernButton:pressed {"
            "   background-color: rgba(0, 122, 255, 0.2);"
            "}";
        m_rippleColor = QColor(0, 122, 255, 60);
        setElevation(0);
        break;
        
    case Floating:
        styleSheet = 
            "ModernButton {"
            "   background-color: #007AFF;"
            "   color: white;"
            "   border: none;"
            "   border-radius: 28px;"
            "   font-size: 14px;"
            "   font-weight: 500;"
            "   min-width: 56px;"
            "   min-height: 56px;"
            "   max-width: 56px;"
            "   max-height: 56px;"
            "}";
        m_rippleColor = QColor(255, 255, 255, 80);
        setElevation(6);
        break;
    }
    
    setStyleSheet(styleSheet);
}

void ModernButton::setElevation(qreal elevation)
{
    if (qFuzzyCompare(m_elevation, elevation))
        return;
        
    m_elevation = elevation;
    updateShadow();
    update();
}

void ModernButton::setRippleColor(const QColor& color)
{
    m_rippleColor = color;
}

void ModernButton::updateShadow()
{
    // Temporarily disable shadow effects to fix painter issues
    // TODO: Implement CSS-style box-shadow alternative
    if (m_shadowEffect) {
        delete m_shadowEffect;
        m_shadowEffect = nullptr;
    }
    setGraphicsEffect(nullptr);
}

void ModernButton::paintEvent(QPaintEvent *event)
{
    QPushButton::paintEvent(event);
    
    if (m_rippleOpacity > 0 && m_rippleRadius > 0) {
        QPainter painter(this);
        painter.setRenderHint(QPainter::Antialiasing);
        
        QColor rippleColor = m_rippleColor;
        rippleColor.setAlphaF(m_rippleOpacity);
        
        painter.setBrush(rippleColor);
        painter.setPen(Qt::NoPen);
        painter.drawEllipse(QPointF(m_rippleCenter), m_rippleRadius, m_rippleRadius);
    }
}

void ModernButton::mousePressEvent(QMouseEvent *event)
{
    startRippleAnimation(event->pos());
    
    if (m_style != Text) {
        m_elevationAnimation->stop();
        m_elevationAnimation->setEndValue(m_elevation * 0.5);
        m_elevationAnimation->start();
    }
    
    QPushButton::mousePressEvent(event);
}

void ModernButton::mouseReleaseEvent(QMouseEvent *event)
{
    if (m_style != Text) {
        m_elevationAnimation->stop();
        qreal targetElevation = m_style == Floating ? 6.0 : 2.0;
        if (underMouse()) {
            targetElevation *= 1.5;
        }
        m_elevationAnimation->setEndValue(targetElevation);
        m_elevationAnimation->start();
    }
    
    QPushButton::mouseReleaseEvent(event);
}

void ModernButton::enterEvent(QEnterEvent *event)
{
    if (m_style != Text) {
        m_elevationAnimation->stop();
        qreal targetElevation = m_style == Floating ? 9.0 : 3.0;
        m_elevationAnimation->setEndValue(targetElevation);
        m_elevationAnimation->start();
    }
    
    QPushButton::enterEvent(event);
}

void ModernButton::leaveEvent(QEvent *event)
{
    if (m_style != Text) {
        m_elevationAnimation->stop();
        qreal targetElevation = m_style == Floating ? 6.0 : 2.0;
        m_elevationAnimation->setEndValue(targetElevation);
        m_elevationAnimation->start();
    }
    
    QPushButton::leaveEvent(event);
}

void ModernButton::startRippleAnimation(const QPoint& center)
{
    m_rippleCenter = center;
    m_rippleRadius = 0;
    m_rippleOpacity = 0.8;
    
    qreal maxRadius = qMax(width(), height());
    
    m_rippleAnimation->stop();
    m_rippleAnimation->setStartValue(0);
    m_rippleAnimation->setEndValue(maxRadius);
    m_rippleAnimation->start();
    
    m_rippleTimer->start();
}

void ModernButton::updateRipple()
{
    m_rippleOpacity = 0;
    update();
}

// Floating Preview Implementation
FloatingPreview::FloatingPreview(QWidget *parent)
    : QWidget(parent)
    , m_settings(nullptr)
    , m_scale(1.0)
    , m_dragging(false)
{
    setupAnimations();
    setMinimumSize(300, 400);
    // 移除固定尺寸限制，允许组件随窗口大小变化
    setAttribute(Qt::WA_Hover, true);
    
    // 浅灰色背景，更舒适的配色
    setStyleSheet(
        "FloatingPreview {"
        "   background-color: #f0f0f0;"
        "   border: none;"
        "}"
    );
}

void FloatingPreview::setupAnimations()
{
    // Scale animation
    m_scaleAnimation = new QPropertyAnimation(this, "scale", this);
    m_scaleAnimation->setDuration(200);
    m_scaleAnimation->setEasingCurve(QEasingCurve::OutCubic);
    
    // Temporarily disable opacity effects to fix painter issues
    // TODO: Implement alternative fade animation
    m_opacityEffect = nullptr;
    m_fadeAnimation = nullptr;
}

void FloatingPreview::setPreviewImage(const QImage& image)
{
    m_previewImage = image;
    renderPreviewPage();
    update();
}

void FloatingPreview::setSettings(const OutputSettings& settings)
{
    m_settings = const_cast<OutputSettings*>(&settings);
    renderPreviewPage();
    update();
}

void FloatingPreview::setScale(qreal scale)
{
    m_scale = qMax(0.5, qMin(2.0, scale));
    update();
}

void FloatingPreview::showPreview()
{
    // Simple show without animation for now
    show();
}

void FloatingPreview::hidePreview()
{
    // Simple hide without animation for now
    hide();
}

void FloatingPreview::updatePreview()
{
    renderPreviewPage();
    update();
}

void FloatingPreview::renderPreviewPage()
{
    if (!m_settings) {
        return;
    }
    
    // Create A4 size preview (210x297mm at 72 DPI for screen)
    QSize a4Size(595, 842); // Standard A4 at 72 DPI
    m_renderedPreview = QImage(a4Size, QImage::Format_ARGB32);
    m_renderedPreview.fill(Qt::white);
    
    QPainter painter(&m_renderedPreview);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setRenderHint(QPainter::TextAntialiasing);
    
    // Calculate margins (mm to pixels at 72 DPI: 1mm = 2.83 pixels)
    const qreal mmToPx = 2.83;
    int marginTop = m_settings->margins.top * mmToPx;
    int marginBottom = m_settings->margins.bottom * mmToPx;
    int marginLeft = m_settings->margins.left * mmToPx;
    int marginRight = m_settings->margins.right * mmToPx;
    
    QRect contentRect(marginLeft, marginTop, 
                     a4Size.width() - marginLeft - marginRight,
                     a4Size.height() - marginTop - marginBottom);
    
    // Draw margin guides (light gray lines)
    painter.setPen(QPen(QColor(200, 200, 200), 1, Qt::DashLine));
    painter.drawRect(QRect(marginLeft, marginTop, 
                          a4Size.width() - marginLeft - marginRight,
                          a4Size.height() - marginTop - marginBottom));
    
    // Draw content area
    if (!m_previewImage.isNull()) {
        QSize scaledSize = m_previewImage.size().scaled(contentRect.size(), Qt::KeepAspectRatio);
        QRect imageRect(0, 0, scaledSize.width(), scaledSize.height());
        imageRect.moveCenter(contentRect.center());
        
        painter.drawImage(imageRect, m_previewImage.scaled(scaledSize, Qt::KeepAspectRatio, Qt::SmoothTransformation));
    } else {
        // Draw placeholder content
        painter.setPen(QPen(QColor(150, 150, 150), 1));
        painter.setBrush(QColor(240, 240, 240));
        QRect placeholderRect = contentRect.adjusted(20, 20, -20, -20);
        painter.drawRect(placeholderRect);
        
        painter.setPen(QColor(100, 100, 100));
        painter.drawText(placeholderRect, Qt::AlignCenter, tr("文档内容区域"));
    }
    
    // Draw header with real font and position
    if (m_settings->header.enabled && !m_settings->header.text.isEmpty()) {
        painter.setFont(m_settings->header.font);
        painter.setPen(m_settings->header.color);
        
        QRect headerRect(marginLeft, 10, 
                        a4Size.width() - marginLeft - marginRight, 
                        marginTop - 20);
        
        Qt::Alignment alignment = Qt::AlignVCenter;
        switch (m_settings->header.position) {
        case HeaderFooterPosition::Left:
            alignment |= Qt::AlignLeft;
            break;
        case HeaderFooterPosition::Center:
            alignment |= Qt::AlignHCenter;
            break;
        case HeaderFooterPosition::Right:
            alignment |= Qt::AlignRight;
            break;
        }
        
        painter.drawText(headerRect, alignment, m_settings->header.text);
    }
    
    // Draw footer with real font and position
    if (m_settings->footer.enabled && !m_settings->footer.text.isEmpty()) {
        painter.setFont(m_settings->footer.font);
        painter.setPen(m_settings->footer.color);
        
        QRect footerRect(marginLeft, a4Size.height() - marginBottom + 10,
                        a4Size.width() - marginLeft - marginRight,
                        marginBottom - 20);
        
        Qt::Alignment alignment = Qt::AlignVCenter;
        switch (m_settings->footer.position) {
        case HeaderFooterPosition::Left:
            alignment |= Qt::AlignLeft;
            break;
        case HeaderFooterPosition::Center:
            alignment |= Qt::AlignHCenter;
            break;
        case HeaderFooterPosition::Right:
            alignment |= Qt::AlignRight;
            break;
        }
        
        QString footerText = m_settings->footer.text;
        footerText.replace("{page}", "1");
        footerText.replace("{totalPages}", "1");
        footerText.replace("{date}", QDate::currentDate().toString("yyyy-MM-dd"));
        
        painter.drawText(footerRect, alignment, footerText);
    }
}

void FloatingPreview::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event)
    
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setRenderHint(QPainter::SmoothPixmapTransform);
    
    // 浅灰色背景，更舒适的配色
    painter.fillRect(rect(), QColor(240, 240, 240));
    
    if (!m_renderedPreview.isNull()) {
        QRect widgetRect = this->rect();
        
        // A4比例: 210mm x 297mm = 1:1.414
        qreal a4Ratio = 297.0 / 210.0;
        qreal widgetRatio = (qreal)widgetRect.height() / widgetRect.width();
        
        QSize a4Size;
        if (widgetRatio > a4Ratio) {
            // 以宽度为准
            a4Size.setWidth(widgetRect.width() - 20); // 留10px边距
            a4Size.setHeight((int)(a4Size.width() * a4Ratio));
        } else {
            // 以高度为准
            a4Size.setHeight(widgetRect.height() - 20); // 留10px边距
            a4Size.setWidth((int)(a4Size.height() / a4Ratio));
        }
        
        // 居中显示A4纸
        QRect a4Rect;
        a4Rect.setSize(a4Size);
        a4Rect.moveCenter(widgetRect.center());
        
        // 绘制A4纸（白色背景）
        painter.fillRect(a4Rect, Qt::white);
        
        // 缩放并绘制预览内容
        QRect contentRect = m_renderedPreview.rect();
        QSize scaledSize = contentRect.size().scaled(a4Rect.size(), Qt::KeepAspectRatio);
        QRect scaledContentRect(0, 0, scaledSize.width(), scaledSize.height());
        scaledContentRect.moveCenter(a4Rect.center());
        
        painter.drawImage(scaledContentRect, m_renderedPreview);
        
        // 不绘制边框，保持A4纸的纯净外观
    } else {
        // 简单的占位符
        painter.setPen(QColor(200, 200, 200));
        painter.drawText(rect(), Qt::AlignCenter, tr("预览将在此显示"));
    }
}

void FloatingPreview::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        m_dragging = true;
        m_lastDragPos = event->pos();
    }
}

void FloatingPreview::mouseMoveEvent(QMouseEvent *event)
{
    if (m_dragging) {
        QPoint delta = event->pos() - m_lastDragPos;
        m_offset += delta;
        m_lastDragPos = event->pos();
        update();
    }
}

void FloatingPreview::wheelEvent(QWheelEvent *event)
{
    qreal delta = event->angleDelta().y() / 1200.0;
    setScale(m_scale + delta);
}

// Modern Slider Implementation
ModernSlider::ModernSlider(Qt::Orientation orientation, QWidget *parent)
    : QWidget(parent)
    , m_orientation(orientation)
    , m_value(0.0)
    , m_minimum(0.0)
    , m_maximum(100.0)
    , m_dragging(false)
    , m_hoverProgress(0.0)
{
    setAttribute(Qt::WA_Hover, true);
    
    m_hoverAnimation = new QPropertyAnimation(this, "hoverProgress", this);
    m_hoverAnimation->setDuration(200);
    m_hoverAnimation->setEasingCurve(QEasingCurve::OutCubic);
}

void ModernSlider::setValue(qreal value)
{
    qreal newValue = qMax(m_minimum, qMin(m_maximum, value));
    if (!qFuzzyCompare(m_value, newValue)) {
        m_value = newValue;
        emit valueChanged(m_value);
        update();
    }
}

void ModernSlider::setMinimum(qreal minimum)
{
    m_minimum = minimum;
    setValue(m_value); // Clamp current value
}

void ModernSlider::setMaximum(qreal maximum)
{
    m_maximum = maximum;
    setValue(m_value); // Clamp current value
}

void ModernSlider::setRange(qreal minimum, qreal maximum)
{
    m_minimum = minimum;
    m_maximum = maximum;
    setValue(m_value); // Clamp current value
}

void ModernSlider::setSuffix(const QString& suffix)
{
    m_suffix = suffix;
    update();
}

QSize ModernSlider::sizeHint() const
{
    if (m_orientation == Qt::Horizontal) {
        return QSize(200, 40);
    } else {
        return QSize(40, 200);
    }
}

void ModernSlider::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event)
    
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);
    
    QRect sliderRect = getSliderRect();
    QRect handleRect = getHandleRect();
    
    // Draw track
    painter.setPen(Qt::NoPen);
    painter.setBrush(QColor(220, 220, 220));
    painter.drawRoundedRect(sliderRect, sliderRect.height() / 2, sliderRect.height() / 2);
    
    // Draw progress
    QRect progressRect = sliderRect;
    if (m_orientation == Qt::Horizontal) {
        progressRect.setWidth((m_value - m_minimum) / (m_maximum - m_minimum) * sliderRect.width());
    } else {
        int progressHeight = (m_value - m_minimum) / (m_maximum - m_minimum) * sliderRect.height();
        progressRect.setTop(sliderRect.bottom() - progressHeight);
    }
    
    painter.setBrush(QColor(0, 122, 255));
    painter.drawRoundedRect(progressRect, progressRect.height() / 2, progressRect.height() / 2);
    
    // Draw handle
    QColor handleColor = QColor(0, 122, 255);
    if (m_hoverProgress > 0) {
        handleColor = QColor::fromHsv(handleColor.hue(), handleColor.saturation(), 
                                     handleColor.value() + m_hoverProgress * 20);
    }
    
    painter.setBrush(handleColor);
    painter.drawEllipse(handleRect);
    
    // Draw value text
    if (!m_suffix.isEmpty() || m_value != 0) {
        QString text = QString::number(m_value, 'f', 1) + m_suffix;
        QFontMetrics fm(font());
        QRect textRect = fm.boundingRect(text);
        textRect.moveCenter(QPoint(width() / 2, height() - 10));
        
        painter.setPen(QColor(100, 100, 100));
        painter.drawText(textRect, Qt::AlignCenter, text);
    }
}

void ModernSlider::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        m_dragging = true;
        updateValueFromPosition(event->pos());
    }
}

void ModernSlider::mouseMoveEvent(QMouseEvent *event)
{
    if (m_dragging) {
        updateValueFromPosition(event->pos());
    }
}

void ModernSlider::mouseReleaseEvent(QMouseEvent *event)
{
    Q_UNUSED(event)
    m_dragging = false;
}

void ModernSlider::wheelEvent(QWheelEvent *event)
{
    qreal delta = event->angleDelta().y() / 120.0;
    qreal step = (m_maximum - m_minimum) / 100.0;
    setValue(m_value + delta * step);
}

QRect ModernSlider::getSliderRect() const
{
    if (m_orientation == Qt::Horizontal) {
        int trackHeight = 4;
        return QRect(10, (height() - trackHeight) / 2, width() - 20, trackHeight);
    } else {
        int trackWidth = 4;
        return QRect((width() - trackWidth) / 2, 10, trackWidth, height() - 20);
    }
}

QRect ModernSlider::getHandleRect() const
{
    int handleSize = 20;
    QRect sliderRect = getSliderRect();
    
    if (m_orientation == Qt::Horizontal) {
        qreal progress = (m_value - m_minimum) / (m_maximum - m_minimum);
        int x = sliderRect.left() + progress * sliderRect.width() - handleSize / 2;
        int y = sliderRect.center().y() - handleSize / 2;
        return QRect(x, y, handleSize, handleSize);
    } else {
        qreal progress = (m_value - m_minimum) / (m_maximum - m_minimum);
        int x = sliderRect.center().x() - handleSize / 2;
        int y = sliderRect.bottom() - progress * sliderRect.height() - handleSize / 2;
        return QRect(x, y, handleSize, handleSize);
    }
}

void ModernSlider::updateValueFromPosition(const QPoint& pos)
{
    QRect sliderRect = getSliderRect();
    
    if (m_orientation == Qt::Horizontal) {
        qreal progress = qMax(0.0, qMin(1.0, 
            qreal(pos.x() - sliderRect.left()) / sliderRect.width()));
        setValue(m_minimum + progress * (m_maximum - m_minimum));
    } else {
        qreal progress = qMax(0.0, qMin(1.0, 
            qreal(sliderRect.bottom() - pos.y()) / sliderRect.height()));
        setValue(m_minimum + progress * (m_maximum - m_minimum));
    }
}

